﻿//The wrapper for our Gremlin project
var playPen = {};
// Array to hold Gremlin
playPen.gremlins = [];
// Constructor for making Gremlin ** PASCAL CASE**
playPen.Gremlin = function (name, moral, image) {
    this.name = name;
    this.moral = moral;
    this.image = image;  
};
//prototype for Gremlin
playPen.Gremlin.prototype.hasBeenFedAfter12 = false;
//Draw table to page
playPen.drawTable = function () {
    var h = "<div class='container'>";
        h += "<div class='row'>";
    for (var i in playPen.gremlins) {
        var currentGremlin = playPen.gremlins[i];
        h += "<div class='col-md-4'>";
        h += "<h1>";
        h += "<i class='" + playPen.getIconName(currentGremlin.moral) + "'></i> ";
        h += currentGremlin.name + "</h1><br/>";
        h += "<img src='" + currentGremlin.image + "' class='img-responsive img-thumbnail gremlin-image'/><br/>";
        h += "<div class='btn btn-danger fa fa-recycle' onclick='playPen.scrapGremlins(" + i + ")'></div>";
        h += "<div class='btn btn-warning fa fa-edit' onclick='playPen.showEdit(" + i + ")'></div>"
        h += "</div>";
    }
    h += "</div>";
    h += "</div>";
    document.getElementById("tableHolder").innerHTML = h;
};

/***************************** Code to draw tables from JAVASCRIPT ********/
//function dataTable(gremlins) {
//    var keys = Object.keys(playpen.gremlins[0]);
//    var headers = keys.map(function (name) {
//        return new UnderlinedCell(new TextCell(name));
//    });
//    var body = data.map(function (row) {
//        return keys.map(function (name) {
//            var value = row[name];
//            // This was changed:
//            if (typeof value == "number")
//                return new RTextCell(String(value));
//            else
//                return new TextCell(String(value));
//        });
//    });
//    return [headers].concat(body);
//}

//console.log(drawTable(dataTable(MOUNTAINS)));
// → … beautifully aligned table
/***********************************************************************/

//Helper Function to pull Icon Names
playPen.getIconName = function (moral) {
    if (moral === "Bad") {
        return "fa fa-qq";
    }
    else if (moral === "Good") {
        return "fa fa-reddit";
    }
    else {
        return "fa fa-paw";
    }

};
/***************** CRUD *******************************/
//Add gremlins to array
playPen.addGremlins = function () {
    "use strict";
    var name, moral, image;
    name = document.getElementById("name");
    moral = document.getElementById("moral");
    image = document.getElementById("image");
    var s = new playPen.Gremlin(name.value, moral.value, image.value);
    playPen.gremlins.push(s);
    image.value = "";
    name.value = "";
    playPen.drawTable();
    playPen.sendGremlins(s);
};
//Delete Gremlin
playPen.scrapGremlins = function (index) {
    playPen.gremlins.splice(index, 1);
    playPen.drawTable();
};
//Show Edit Gremlin
playPen.showEdit = function (index) {
    var gremlin = playPen.gremlins[index];
    document.getElementById("editTitle").innerHTML = "Gremlin information for the " + gremlin.name;
    document.getElementById("editName").value = gremlin.name;
    document.getElementById("editImage").value = gremlin.image;
    document.getElementById("editMoral").value = gremlin.moral;
    document.getElementById("editHasBeenFedAfter12").value = gremlin.hasBeenFedAfter12.toString();
    document.getElementById("saveChangesBtn").onclick = function () { playPen.saveEdit(index); };
    $("#editModal").modal();

};
//Save Edit Gremlin
playPen.saveEdit = function (index) {
    var gremlin = playPen.gremlins[index];
    gremlin.name = document.getElementById("editName").value;
    gremlin.image = document.getElementById("editImage").value;
    gremlin.moral = document.getElementById("editMoral").value;
    if (document.getElementById("editHasBeenFedAfter12").value ==="true") {
        gremlin.hasBeenFedAfter12 = true;
    }
    else {
        delete gremlin.hasBeenFedAfter12;
    }
    //playPen.gremlins[index].name = document.getElementById("editName").value;
    $("#editModal").modal("hide");
    playPen.drawTable();
};
/******************End CRUD****************************/
/*****************AJAX*********************************/
//Send to Firebase
playPen.sendGremlins = function (gremlin) {
    //Instantiate a new XMLHTTP request object
    console.log(gremlin);
    var request = new XMLHttpRequest();
    //Puts postage and Address on the envelope
    request.open("POST", "https://brilliant-fire-2547.firebaseio.com/.json", true);
    //Defines what happens when the response loads
    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            //Got a valid response
            alert(this.response); //to see if we got data back from firebase
        }
        else {
            console.log(" Error" + this.status + ":" + this.response);
        }

    };
    //What happens if the request load never occurs
    request.onerror = function () {
        console.log("Communication error");
    };
    //Sends the request
    request.send(JSON.stringify(gremlin));

};



//Pull from Firebase
playPen.getGremlins = function () {

    //Instantiate a new XMLHTTP request object
    var request = new XMLHttpRequest();
    //Puts postage and Address on the envelope
    request.open("GET", "https://brilliant-fire-2547.firebaseio.com/.json", true);
    //Defines what happens when the response loads
    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            //Got a valid response
            alert(this.response); //to see if we got data back from firebase
            // got string turn back to object
            var data = JSON.parse(this.response);
            for (var x in data) {   //sending data back from all gremlins have to loop and extract
                data[x].__proto__ = playPen.Gremlin.prototype; // need to update prototype 
                data[x].key = x; // used to store key
                playPen.gremlins.push(data[x]);  //pushing ship back to array *** Figure out what X is!
            }
            playPen.drawTable();  //write to table
        }
        else {
            console.log("Error" + this.status + ":" + this.response);
        }

    };
    //What happens if the request load never occurs
    request.onerror = function () {
        console.log("Communication error");
    };
    //Sends the request
    request.send();



};
//NEED UPDATE AND DELETE

/******************End AJAX***************************/
//Seed Function
playPen.seed = function () {
    playPen.gremlins.push(new playPen.Gremlin("Gizmo", "Good", "http://camikaos.files.wordpress.com/2013/10/gizmo.png"));
    playPen.gremlins.push(new playPen.Gremlin("Genius", "Bad", "http://media.melty.fr/article-1492029-ajust_930/voila-ce-que-devient-un-gentil-mogwai-si.jpg"));
    playPen.gremlins.push(new playPen.Gremlin("Girl?", "Other", "http://i1.ytimg.com/vi/XiVB3ZHCkGM/maxresdefault.jpg"));
    playPen.gremlins.push(new playPen.Gremlin("Gizmodo?", "Other", "/gizmo.png"));
    playPen.drawTable();
};
//Clear All
playPen.clearAll = function () {
    playPen.gremlins = [];
    playPen.drawTable();
};
//Run Seed Function
playPen.seed();
playPen.getGremlins();